package com.ruoyi.campus.utils;

import org.apache.commons.io.FilenameUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 媒体文件处理工具类
 * 
 * @author campus-alarm
 * @date 2024-01-01
 */
public class MediaUtils
{
    /**
     * 计算图片缩放后的尺寸
     */
    public static Dimension calculateScaledDimension(int originalWidth, int originalHeight, 
                                                   int maxWidth, int maxHeight, boolean keepAspectRatio)
    {
        if (!keepAspectRatio) {
            return new Dimension(maxWidth, maxHeight);
        }

        double scaleX = (double) maxWidth / originalWidth;
        double scaleY = (double) maxHeight / originalHeight;
        double scale = Math.min(scaleX, scaleY);

        int newWidth = (int) (originalWidth * scale);
        int newHeight = (int) (originalHeight * scale);

        return new Dimension(newWidth, newHeight);
    }

    /**
     * 获取图片基本信息
     */
    public static Map<String, Object> getImageInfo(InputStream inputStream) throws IOException
    {
        BufferedImage image = ImageIO.read(inputStream);
        if (image == null) {
            throw new IOException("无法读取图片");
        }

        Map<String, Object> info = new HashMap<>();
        info.put("width", image.getWidth());
        info.put("height", image.getHeight());
        info.put("colorModel", image.getColorModel().getClass().getSimpleName());
        info.put("hasAlpha", image.getColorModel().hasAlpha());
        info.put("pixelSize", image.getWidth() * image.getHeight());

        return info;
    }

    /**
     * 将BufferedImage转换为字节数组
     */
    public static byte[] bufferedImageToBytes(BufferedImage image, String format) throws IOException
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, format, baos);
        return baos.toByteArray();
    }

    /**
     * 计算文件大小的可读格式
     */
    public static String formatFileSize(long bytes)
    {
        if (bytes < 1024) {
            return bytes + " B";
        } else if (bytes < 1024 * 1024) {
            return String.format("%.1f KB", bytes / 1024.0);
        } else if (bytes < 1024 * 1024 * 1024) {
            return String.format("%.1f MB", bytes / (1024.0 * 1024));
        } else {
            return String.format("%.1f GB", bytes / (1024.0 * 1024 * 1024));
        }
    }

    /**
     * 计算压缩率
     */
    public static double calculateCompressionRatio(long originalSize, long compressedSize)
    {
        if (originalSize == 0) return 0;
        return (double) compressedSize / originalSize;
    }

    /**
     * 获取视频分辨率描述
     */
    public static String getResolutionDescription(int width, int height)
    {
        if (width >= 1920 && height >= 1080) {
            return "1080p";
        } else if (width >= 1280 && height >= 720) {
            return "720p";
        } else if (width >= 854 && height >= 480) {
            return "480p";
        } else if (width >= 640 && height >= 360) {
            return "360p";
        } else {
            return width + "x" + height;
        }
    }

    /**
     * 解析分辨率字符串
     */
    public static Dimension parseResolution(String resolution)
    {
        if (resolution == null) return null;

        switch (resolution.toLowerCase()) {
            case "1080p":
                return new Dimension(1920, 1080);
            case "720p":
                return new Dimension(1280, 720);
            case "480p":
                return new Dimension(854, 480);
            case "360p":
                return new Dimension(640, 360);
            case "240p":
                return new Dimension(426, 240);
            default:
                // 尝试解析 "1920x1080" 格式
                if (resolution.contains("x")) {
                    String[] parts = resolution.split("x");
                    if (parts.length == 2) {
                        try {
                            int width = Integer.parseInt(parts[0]);
                            int height = Integer.parseInt(parts[1]);
                            return new Dimension(width, height);
                        } catch (NumberFormatException e) {
                            return null;
                        }
                    }
                }
                return null;
        }
    }

    /**
     * 格式化时长（秒转换为 HH:mm:ss 格式）
     */
    public static String formatDuration(double seconds)
    {
        int totalSeconds = (int) seconds;
        int hours = totalSeconds / 3600;
        int minutes = (totalSeconds % 3600) / 60;
        int secs = totalSeconds % 60;

        if (hours > 0) {
            return String.format("%02d:%02d:%02d", hours, minutes, secs);
        } else {
            return String.format("%02d:%02d", minutes, secs);
        }
    }

    /**
     * 解析时长字符串（HH:mm:ss 或 mm:ss 格式转换为秒）
     */
    public static int parseDuration(String duration)
    {
        if (duration == null || duration.trim().isEmpty()) {
            return 0;
        }

        String[] parts = duration.split(":");
        try {
            if (parts.length == 3) {
                // HH:mm:ss
                int hours = Integer.parseInt(parts[0]);
                int minutes = Integer.parseInt(parts[1]);
                int seconds = Integer.parseInt(parts[2]);
                return hours * 3600 + minutes * 60 + seconds;
            } else if (parts.length == 2) {
                // mm:ss
                int minutes = Integer.parseInt(parts[0]);
                int seconds = Integer.parseInt(parts[1]);
                return minutes * 60 + seconds;
            } else if (parts.length == 1) {
                // ss
                return Integer.parseInt(parts[0]);
            }
        } catch (NumberFormatException e) {
            return 0;
        }

        return 0;
    }

    /**
     * 计算音频比特率的可读格式
     */
    public static String formatBitrate(long bitrate)
    {
        if (bitrate < 1000) {
            return bitrate + " bps";
        } else if (bitrate < 1000000) {
            return String.format("%.0f kbps", bitrate / 1000.0);
        } else {
            return String.format("%.1f Mbps", bitrate / 1000000.0);
        }
    }

    /**
     * 获取音频质量描述
     */
    public static String getAudioQualityDescription(long bitrate)
    {
        if (bitrate >= 320000) {
            return "极高质量";
        } else if (bitrate >= 256000) {
            return "高质量";
        } else if (bitrate >= 192000) {
            return "好质量";
        } else if (bitrate >= 128000) {
            return "标准质量";
        } else if (bitrate >= 96000) {
            return "中等质量";
        } else {
            return "低质量";
        }
    }

    /**
     * 验证图片尺寸是否在允许范围内
     */
    public static boolean isValidImageSize(int width, int height, int maxWidth, int maxHeight, 
                                         int minWidth, int minHeight)
    {
        return width >= minWidth && height >= minHeight && 
               width <= maxWidth && height <= maxHeight;
    }

    /**
     * 计算图片的宽高比
     */
    public static double calculateAspectRatio(int width, int height)
    {
        if (height == 0) return 0;
        return (double) width / height;
    }

    /**
     * 判断图片是否为横向
     */
    public static boolean isLandscape(int width, int height)
    {
        return width > height;
    }

    /**
     * 判断图片是否为纵向
     */
    public static boolean isPortrait(int width, int height)
    {
        return height > width;
    }

    /**
     * 判断图片是否为正方形
     */
    public static boolean isSquare(int width, int height)
    {
        return width == height;
    }

    /**
     * 获取支持的图片格式
     */
    public static String[] getSupportedImageFormats()
    {
        return new String[]{"jpg", "jpeg", "png", "gif", "bmp", "webp"};
    }

    /**
     * 获取支持的音频格式
     */
    public static String[] getSupportedAudioFormats()
    {
        return new String[]{"mp3", "wav", "aac", "ogg", "flac", "m4a"};
    }

    /**
     * 获取支持的视频格式
     */
    public static String[] getSupportedVideoFormats()
    {
        return new String[]{"mp4", "avi", "mov", "wmv", "flv", "webm", "mkv"};
    }

    /**
     * 检查文件扩展名是否受支持
     */
    public static boolean isSupportedFormat(String fileName, String mediaType)
    {
        String extension = FilenameUtils.getExtension(fileName).toLowerCase();
        
        switch (mediaType.toLowerCase()) {
            case "image":
                return java.util.Arrays.asList(getSupportedImageFormats()).contains(extension);
            case "audio":
                return java.util.Arrays.asList(getSupportedAudioFormats()).contains(extension);
            case "video":
                return java.util.Arrays.asList(getSupportedVideoFormats()).contains(extension);
            default:
                return false;
        }
    }

    /**
     * 生成唯一的处理文件名
     */
    public static String generateProcessedFileName(String originalFileName, String processType)
    {
        String baseName = FilenameUtils.getBaseName(originalFileName);
        String extension = FilenameUtils.getExtension(originalFileName);
        String timestamp = String.valueOf(System.currentTimeMillis());
        
        return String.format("%s_%s_%s.%s", baseName, processType, timestamp, extension);
    }
} 